/**
  * @Description: 
  * @Author: 
  * @Date: 2023-08-16 09:14:09
  * @LastEditor: 
  * @LastEditTime: 2023-09-12 10:43:42
  
  */
 

import apiList from './api.js';
import { BASE_URL, SIGN } from '@/env.js';
import store from '@/common/store/index.js'
import ase256 from './ase256.js';

// 组装接口路径
const getApiPath = path => {
	let apiArray = path.split("."),
		api = apiList
	apiArray.forEach(v => {
		api = api[v]
	});
	return api
}

// 发起请求的函数
const request = (path, data, error = true) => {
	
	if(!BASE_URL) {
		uni.showModal({ title: '未检测到域名地址，请联系管理员' })
		throw (`未检测到域名, 已阻止此次API请求`)
	}
	const api = getApiPath(path)
	if(!api) throw (`接口未定义, 已阻止此次API请求`)
	let apiCommon = uni.getStorageSync('commonUrl');
	let domain=BASE_URL
		
	//console.log(BASE_URL);
	if(apiCommon.apiUrl){
		domain=apiCommon.apiUrl//'https://tpyy.cn'//apiCommon.apiUrl//
	}
	const url = domain + api.url,
		  method = api.method
		   let $requestObj={}
			//先做签名
			 console.log("请求数据",path)
			  console.log("请求数据",data)
			 let $obj={};
			 $obj.timestamp=Math.floor(Date.now() / 1000)
			 $obj.system = 2
			 let $signData={};
			 ////console.log("请求参数判断",typeof data ==='object')
			 if(typeof data ==='object'){
				 $signData=Object.assign({}, $obj, data);
			 }else{
				 $signData=$obj;
			 }
			
			////console.log("对象",$signData)
			let $sdata = sort_ascii($signData);//准备加密的字符串
			let $encode_sign = ase256.md5Encrypt($sdata);//md5加密
			$signData.$encode_sign =$encode_sign
			const $cryp=ase256.encryptWithAES256CBC(JSON.stringify($signData))//ase256加密
			$requestObj['post-data']=$cryp
			
			
			
		
	// 通过Promise封装请求, 返回异步请求结果
	return new Promise(async (resolve, reject) => {
		//let abc = {sslVerify:false}
		//data= {...data,...abc}
		
		uni.request({
			url,
			data:  $requestObj,
			method,
			header: {
				'Content-Type': method === 'GET' ? 'application/json' : 'application/x-www-form-urlencoded',
				'Token': store.state.user.token || '',
				'suffix': SIGN || ''
			},
			success: res => {
				//验签
				//ase256解密
				let encData=res.data.data
				let dat=ase256.decryptWithAES256CBC(encData);
				console.log("响应数据的接口",api.url)
				console.log("响应数据",dat);
				//console.log("旧的响应接口",res)
				if(res.statusCode === 200) {
					if(dat.code != 1 && dat.code != 1314) {
						error && uni.showToast({
							title: dat.msg || `error => ${BASE_URL || 'NULL'} => ${SIGN || 'NULL'}`,
							icon: 'none',
							mask: true,
							duration: 3000
						})
					}
					if(dat.code === 401) {
						//console.log("401---")
						store.dispatch('user/logout')
						error && uni.showModal({
							title: '系统提示',
							content: '本操作需要您进行登录验证',
							success: res => {
								if(res.confirm) {
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}
							}
						})
					}
				} else if (res.statusCode === 401){
					//console.log("200---")
					if(dat.code === 401) {
						//console.log("401---")
						uni.navigateTo({
							url: '/pages/login/login'
						})
						store.dispatch('user/logout')
						error && uni.showModal({
							title: '系统提示',
							content: '本操作需要您进行登录验证',
							success: res => {
								if(res.confirm) {
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}
							}
						})
					}
				} else {
					
					error && uni.showToast({
						title: res.statusCode.toString(),
						icon: 'none'
					})
				}

				resolve(dat)
			},
			fail: err => {
				//console.log(err,"111111111111")
				uni.showToast({
					title: err.errMsg,
					icon: 'none',
					duration: 3000
				})
				// uni.showToast({
				// 	title: `服务器开小差 => ${BASE_URL || 'NULL'} => ${SIGN || 'NULL'}`,
				// 	icon: 'none'
				// })
				reject(err)
			}
		})
	})
}
        /**按ascii码从小到大排序
         *
         * @param obj
         * @returns {string}
         */
        function sort_ascii(obj) {
            let arr = new Array();
            let num = 0;
            for (let i in obj) {
                arr[num] = i;
                num++;
            }
            let sortArr = arr.sort();
            //let sortObj = {};    //完成排序值
            let str = '';             //自定义排序字符串
            for (let i in sortArr) {
                str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
                //sortObj[sortArr[i]] = obj[sortArr[i]];
            }
            //去除两侧字符串
            let char = '&'
            str = str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
            str =str+"&B68m@%zg32_%u*vHUlE4WkS&1J6%%xmU@fN"
            return str;
            //return sortObj;
        }

        


export default request